package westeel.dataserver.handler;

import com.alibaba.fastjson.JSON;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.Map;

/**
 * @description: web全局异常处理
 * @author: DT
 * @date: 2021/4/19 21:17
 * @version: v1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public Map  exceptionHandler(Exception e){
        logger.error("web  exception",e);
        Map ret = new HashedMap(){{
            put("err", "内部错误:"+e.getMessage());
            put("code",-1);
        }};
        return ret;// JSON.toJSONString(ret);
    }
    @ExceptionHandler(value = SQLException.class)
    @ResponseBody
    public Map exceptionHandler(SQLException e){
        logger.error("sql exception",e);
        Map ret = new HashedMap(){{
            put("err","请求语句出错:"+e.getMessage());
            put("code",-1);
        }};
        return ret;
    }
}
